package orbitorcensor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import jsprintorbitor.bridge2native.BridgeUtils;
import jsprintorbitor.experiment.INativeObjectHolder;
import laboratoryQ.computation.BaseUtils;
import laboratoryQ.junit.ignore.patch.BaseTestCase;

public class TestObjectsLifetime extends BaseTestCase {
	static {
		System.loadLibrary(BridgeUtils.getSprintOrbiterSOName());
		System.loadLibrary("orbitercensor");
	}
	
	static void init() {
		// automatically calls System.loadLibrary("orbitorcensor");
	}
	
	public int[] createdObjectsNotes;
	public int[] destroyedObjectsNotes;
	public void testNativeObjectHolder() {
		createdObjectsNotes = new int[10];
		Arrays.fill(createdObjectsNotes, -1);
		destroyedObjectsNotes = new int[10];
		Arrays.fill(destroyedObjectsNotes, -1);
		
		assertEquals("[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]", Arrays.toString(createdObjectsNotes));
		assertEquals("[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]", Arrays.toString(destroyedObjectsNotes));
		
		int[] sptrAndDestructor = generateFakeNativeObject();
		INativeObjectHolder holder = BridgeUtils.newNativeObjectHolder(sptrAndDestructor);
		try {
			assertEquals( "[1, -1, -1, -1, -1, -1, -1, -1, -1, -1]", Arrays.toString(createdObjectsNotes));
			assertEquals("[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1]", Arrays.toString(destroyedObjectsNotes));
		} finally {
			BaseUtils.dispose(holder);
		}
		assertEquals("[1, -1, -1, -1, -1, -1, -1, -1, -1, -1]", Arrays.toString(createdObjectsNotes));
		assertEquals("[1, -1, -1, -1, -1, -1, -1, -1, -1, -1]", Arrays.toString(destroyedObjectsNotes));
		
		List<INativeObjectHolder> nobjs = new ArrayList<INativeObjectHolder>();
		try {
			for (int i = 0; i < 5; i++) {
				nobjs.add(BridgeUtils.newNativeObjectHolder(generateFakeNativeObject()));
			}
			assertEquals("[1, 2, 3, 4, 5, 6, -1, -1, -1, -1]", Arrays.toString(createdObjectsNotes));
			assertEquals("[1, -1, -1, -1, -1, -1, -1, -1, -1, -1]", Arrays.toString(destroyedObjectsNotes));
		} finally {
			BaseUtils.disposeItr(nobjs);
		}
		assertEquals("[1, 2, 3, 4, 5, 6, -1, -1, -1, -1]", Arrays.toString(createdObjectsNotes));
		assertEquals("[1, 2, 3, 4, 5, 6, -1, -1, -1, -1]", Arrays.toString(destroyedObjectsNotes));
	}

	private native int[] generateFakeNativeObject();

	public void testSameGraphGenered() {
		// CensorSupport.cpp::Java_orbitorcensor_TestObjectsLifetime_nativeTestSameGraphGenered
		nativeTestSameGraphGenered();
	}

	private static native void nativeTestSameGraphGenered();
}
